package com.ssmTest.service.impl;


import com.ssmTest.model.MachineUserInformation;
import com.ssmTest.model.Order;
import com.ssmTest.model.UserInformation;
import com.ssmTest.service.IMachineUserInformationService;
import com.ssmTest.service.IReadExcelService;
import com.ssmTest.service.IUserInformationService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import java.io.*;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

@Service("readExcelService")
public class ReadExcel implements IReadExcelService{
    @Autowired
    private IMachineUserInformationService iMachineUserInformationService;
    @Autowired
    private IUserInformationService iUserInformationService;
    //总行数
    private int totalRows = 0;
    //总条数
    private int totalCells = 0;
    //错误信息接收器
    private String errorMsg;

    //构造方法
    public ReadExcel() {

    }

    //获取总行数
    public int getTotalRows() {
        return totalRows;
    }

    //获取总列数
    public int getTotalCells() {
        return totalCells;
    }

    //获取错误信息
    public String getErrorInfo() {
        //    errorfilename表示文件格式错误
        //    success 导入成功
        //    error    导入失败
        return errorMsg;
    }

    /**
     * 读EXCEL文件，获取信息集合
     */
    public List<Order> getExcelInfo(MultipartFile mFile) {
//        String fileName = mFile.getOriginalFilename(); //获取文件名
//        try {
//
//            boolean isExcel2003 = true;// 根据文件名判断文件是2003版本还是2007版本
//            if (isExcel2007(fileName)) {
//                isExcel2003 = false;
//            }
//
//            //将文件转化成File，便于以后处理
//            CommonsMultipartFile cf = (CommonsMultipartFile) mFile;
//            DiskFileItem fi = (DiskFileItem) cf.getFileItem();
//
//            //File f = fi.getStoreLocation();
//
//            //InputStream is = new FileInputStream(f);
//            InputStream is = fi.getInputStream();
//            List<Order> tableList = createExcel(is, isExcel2003);
//            return tableList;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        List<Order> tableList = null;
        return tableList;
    }

    /**
     * 根据excel里面的内容读取客户信息
     *
     * @param is          输入流
     * @param isExcel2003 excel是2003还是2007版本
     * @return
     * @throws IOException
     */
    public List<Order> createExcel(InputStream is, boolean isExcel2003) {
        try {
            Workbook wb = null;
            if (isExcel2003) {// 当excel是2003时,创建excel2003
                wb = new HSSFWorkbook(is);
            } else {// 当excel是2007时,创建excel2007
                wb = new XSSFWorkbook(is);
            }
            List<Order> tableList = null;
            try {
                tableList = readExcelValue(wb);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }// 读取Excel里面客户的信息
            return tableList;
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<Order> tableList = null;
        return tableList;
    }

    /**
     * 读取Excel里面客户的信息
     *
     * @param wb
     * @return
     * @throws ParseException
     */
    public List<Order> readExcelValue(Workbook wb) throws ParseException {
        // 得到第一个shell
        Sheet sheet = wb.getSheetAt(0);
        // 得到Excel的行数
        this.totalRows = sheet.getPhysicalNumberOfRows();
        // 得到Excel的列数(前提是有行数)
        if (totalRows > 1 && sheet.getRow(0) != null) {
            this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
        }
        return readTableValue(sheet);
    }


    public List<Order> readTableValue(Sheet sheet) throws ParseException {

        List<Order> tableList = new ArrayList<Order>();
//        // 循环Excel行数
//        for (int r = 1; r < totalRows; r++) {
//            Row row = sheet.getRow(r);
//            if (row == null) {
//                continue;
//            }
//            Order table = new Order();
//            // 循环Excel的列
//            for (int c = 0; c < 8; c++) {
//                Cell cell = row.getCell(c);
//                if (null != cell) {
//                    if (c == 0) {                   //工程编号
//                        byte b[] = cell.getStringCellValue().getBytes();
//                        String t = new String(b);
//                        table.setEngin_number(t);
//                    } else if (c == 1) {                  //工程名称
//                        byte b[] = cell.getStringCellValue().getBytes();
//                        String t = new String(b);
//                        table.setEngin_name(t);
//                    } else if (c == 2) {                  //用热面积
//                        String value = String.valueOf(cell.getNumericCellValue());
//                        double d = Double.valueOf(value);
//                        table.setHeat_area(d);
//                    } else if (c == 3) {                  //用热时间
//                        if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
//                            String value = String.valueOf(cell.getNumericCellValue());
//                            table.setHeat_time(value);
//                        } else {
//                            table.setHeat_time(cell.getStringCellValue());
//                        }
//                    } else if (c == 4) {                  //所属项目部
//                        table.setProject_department(cell.getStringCellValue());
//                    } else if (c == 5) {                  //所属公司
//                        table.setSubsidiary_company(cell.getStringCellValue());
//                    } else if (c == 6) {                  //委托以及图纸下发时间
//                        if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
//                            String value = String.valueOf(cell.getNumericCellValue());
//                            table.setCommission_time(value);
//                        } else {
//                            String s = cell.getStringCellValue();
//                            table.setCommission_time(Dateprocess.tostand(s));
//                        }
//                    }
//                }
//            }
//
//            //设置材料预计提报时间
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
//            String s = table.getCommission_time();
//            Date date = sdf.parse(Dateprocess.tostand(s));
//            Calendar cal = Calendar.getInstance();
//            cal.setTime(date);
//            cal.add(Calendar.DATE, 5);// 今天+1天
//            if(cal.get(Calendar.DAY_OF_WEEK)==Calendar.SATURDAY)
//                cal.add(Calendar.DATE, 2);// 今天+1天
//            else if(cal.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY)
//                cal.add(Calendar.DATE, 1);// 今天+1天
//            table.setMaterial_presentation(sdf.format(cal.getTime()));
//
//
//            //设置预计工期
//            double d = table.getHeat_area()/10000;
//            int i = (new Double(d)).intValue();
//            if(i<=3){
//                table.setProject_timelimit(25);
//            }else if(i<=5){
//                table.setProject_timelimit(30);
//            }else if(i<=10){
//                table.setProject_timelimit(40);
//            }else if(i<=20){
//                table.setProject_timelimit(50);
//            }else if(i<=40){
//                table.setProject_timelimit(60);
//            }else if(i<=50){
//                table.setProject_timelimit(80);
//            }else{
//                table.setProject_timelimit(100);
//            }
//            // 添加到list
//            tableList.add(table);
//        }
        return tableList;
    }


    /**
     * 验证EXCEL文件
     *
     * @param filePath
     * @return
     */
    public boolean validateExcel(String filePath) {
        if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) {
            errorMsg = "errorfilename";
            return false;
        }
        return true;
    }

    //生成Excel表
    public void generaExcel(List<Order> list) {
        HSSFWorkbook wb = new HSSFWorkbook();
        //生成一个sheet1
        HSSFSheet sheet = wb.createSheet("sheet1");
        //为sheet1生成第一行，用于放表头信息
        HSSFRow row = sheet.createRow(0);

        row.setHeight((short) 330);
        //第一行的第一个单元格的值为  ‘序号’
        HSSFCell cell = row.createCell((short) 0);
        cell.setCellValue("订单编号");

        cell = row.createCell((short) 1);
        cell.setCellValue("订单成立时间");

        cell = row.createCell((short) 2);
        cell.setCellValue("订单名称");

        cell = row.createCell((short) 3);
        cell.setCellValue("订单甲方id");

        cell = row.createCell((short) 4);
        cell.setCellValue("订单乙方id");

        cell = row.createCell((short) 5);
        cell.setCellValue("订单开始时间");

        cell = row.createCell((short) 6);
        cell.setCellValue("订单结束时间");

        cell = row.createCell((short) 7);
        cell.setCellValue("订单备注");

        cell = row.createCell((short) 8);
        cell.setCellValue("订单状态");

        UserInformation userInformation = new UserInformation();
        MachineUserInformation machineUserInformation = new MachineUserInformation();
        for (int j = 0; j < 10; j++)
            sheet.setColumnWidth(j, 20 * 256);
        //获得List中的数据，并将数据放到Excel中
        int i = 0;
        for (Order table : list) {
            row = sheet.createRow(i + 1);
            row.setHeight((short) 330);

            cell = row.createCell((short) 0);
            cell.setCellValue(table.getId());

            cell = row.createCell((short) 1);
            cell.setCellValue(table.getTime());

            cell = row.createCell((short) 2);
            cell.setCellValue(table.getTitle());

            cell = row.createCell((short) 3);
            cell.setCellValue(table.getFirst_party());

            cell = row.createCell((short) 4);
            cell.setCellValue(table.getSecond_party());

            if (table.getType() == 1) {
                userInformation = iUserInformationService.selectUserInformation(table.getInformation());
                cell = row.createCell((short) 5);
                cell.setCellValue(userInformation.getOperate_time_start());

                cell = row.createCell((short) 6);
                cell.setCellValue(userInformation.getOperate_time_end());


                cell = row.createCell((short) 7);
                cell.setCellValue(userInformation.getRemarks());
            } else if (table.getType() == 2) {
                machineUserInformation = iMachineUserInformationService.selectMachineUserInformation(table.getInformation());
                cell = row.createCell((short) 5);
                cell.setCellValue(machineUserInformation.getOperate_time_start());

                cell = row.createCell((short) 6);
                cell.setCellValue(machineUserInformation.getOperate_time_end());


                cell = row.createCell((short) 7);
                cell.setCellValue(machineUserInformation.getRemarks());
            }
            String type = new String();
            if (table.getType() == 0)
                type = "初始订单";
            else if (table.getType() == 1)
                type = "定金已付";
            else if (table.getType() == 2)
                type = "完工待结算";
            else if (table.getType() == 3)
                type = "订单结算完毕";
            cell = row.createCell((short) 8);
            cell.setCellValue(type);

            i++;
        }

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(new File("D:\\upload\\date.xls"));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            wb.write(fos);
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    // @描述：是否是2003的excel，返回true是2003
    public  boolean isExcel2003(String filePath) {
        return filePath.matches("^.+\\.(?i)(xls)$");
    }

    //@描述：是否是2007的excel，返回true是2007
    public  boolean isExcel2007(String filePath) {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
    }
}
